package org.smart4j.plugin.security;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smart4j.plugin.security.exception.AuthcException;
import org.smart4j.plugin.security.exception.AuthzException;

/**
 * Created by Wangminze on 2016/12/31.
 * Description:Security助手类
 */
public final class SecurityHelper {
    private static final Logger LOGGER = LoggerFactory.getLogger(SecurityHelper.class);


    /**
     * author: Wangminze
     * date: 2016/12/31
     * description:  登录
     * @param username
     * @param password
     * @throws AuthzException
     */
    public static void login(String username, String password){

        Subject currentUser = SecurityUtils.getSubject();
        if (currentUser != null){
            UsernamePasswordToken token = new UsernamePasswordToken(username,password);
            try {
                currentUser.login(token);
            }catch (AuthenticationException e){
                LOGGER.error("Login failure", e);
                throw new AuthcException(e);
            }
        }

    }

    /**
     * author: Wangminze
     * date: 2016/12/31
     * description:  注销
     */
    public static void logout(){
        Subject currentUser = SecurityUtils.getSubject();
        if (currentUser != null){
            currentUser.logout();
        }
    }

}
